package com.ma.admin.handler

import com.ma.admin.dao.TripsRepository
import com.ma.admin.model.Orders
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import xyz.erupt.annotation.`fun`.DataProxy
import xyz.erupt.core.exception.EruptWebApiRuntimeException
import java.util.*

/**
 * 订单数据校验和处理
 *
 * @author yong
 * @date 2021/2/6 20:17
 */
@Component
class OrderDataProxy : DataProxy<Orders> {
    @Autowired
    lateinit var tripsRepository: TripsRepository

    /**
     * 在进行数据更新前对一些更改的字段进行数据校验
     * 因在字典里坐席的id分别为11和22，所以这里需要修改为1和2
     *
     * @param orders 订单
     * @return void
     * @author yong
     * @date 2021/2/6 21:57
     */
    override fun beforeUpdate(orders: Orders) { //校验身份证号
        val orderPassengerIdentityNum = orders.orderPassengerIdentityNum
        val regexIdentity = "^\\d{15}|\\d{18}$".toRegex()
        if (!orderPassengerIdentityNum.matches(regexIdentity)) throw EruptWebApiRuntimeException("请请输入正确的身份证号!")

        //校验联系人手机号
        val orderLinkmanPhone = orders.orderLinkmanPhone
        val regexPhone = "0?(13|14|15|18|17)[0-9]{9}".toRegex()
        if (!orderLinkmanPhone.matches(regexPhone)) throw EruptWebApiRuntimeException("请请输入正确的手机号!")

        //修改坐席的值
        if (orders.orderSeatLevel == 11)
            orders.orderSeatLevel = 1
        else
            orders.orderSeatLevel = 2
    }

    /**
     * 在数据更改后更改订单表的更新时间
     *
     * @param orders 订单
     * @return void
     * @author yong
     * @date 2021/2/6 21:57
     */
    override fun afterUpdate(orders: Orders) { //更改时设置修改时间
        val date = Date()
        orders.orderUpdateTime = (date)
    }

    /**
     * 在查询时对每个订单的状态进行更新，如果订单的车次已发车，则状态也要相应改变
     *
     * @param list 查询到订单列表
     * @return void
     * @author yong
     * @date 2021/2/7 20:17
     */
    override fun afterFetch(list: Collection<MutableMap<String, Any?>>) {
        list.forEach { order ->
            val orderStatus = order["order_status"] as Int
            if (orderStatus == 0) {
                val trips = tripsRepository.findById(order["trips_trips_id"] as Int)
                trips.ifPresent { trip ->
                    if (trip.tripsStartTime.time < Date().time) order["order_status"] = "已发车" //设置为已经发车
                }
            }
        }
    }
}